package com.online.shopping.controller;

import com.online.shopping.entity.RespBean;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class FileController {

	@Value("${minio.endpoint}")
	private String endpoint;
	@Value("${minio.bucketName}")
	private String bucketName;
	@Value("${minio.accessKey}")
	private String accessKey;
	@Value("${minio.secretKey}")
	private String secretKey;

	@PostMapping("/uploadFile")
//	@CrossOrigin("*")
	public RespBean uploadFile(MultipartFile file){
		System.out.println("进入uploadFile");
		try{
			// 创建MinioClient实例
			MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);

			// 判断文件夹是否为空，是则创建
			boolean isExist = minioClient.bucketExists(bucketName);
			if (!isExist){
				// 设置文件夹属性
				minioClient.makeBucket(bucketName);
				minioClient.setBucketPolicy(bucketName, "*.*", PolicyType.READ_ONLY);
			}

			// 设置存储对象的名称
			String filename = file.getOriginalFilename();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String objectName = sdf.format(new Date())+"/"+filename;

			// 把存储对象放到存储桶中
			minioClient.putObject(bucketName, objectName, file.getInputStream(), file.getContentType());
			System.out.println("文件上传成功!");

			String objectURL = minioClient.getObjectUrl(bucketName, objectName);
			System.out.println(objectURL);

			return RespBean.ok("文件上传成功!", objectURL);
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("文件上传失败!");
		}

	}
}
